﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Chisel.Core
{
	/// <summary>
	/// Base class for actors that are children to entities.
	/// </summary>
	public abstract class EntityChild : Actor
	{

		public EntityChild(string label)
			: base()
		{
			_label = new TextBlock() {
				Padding = new Thickness(6, 2, 6, 2)
			};

			Label = label;
		}


		public override DiagramCanvas ParentCanvas
		{
			get
			{
				if (Parent == null)
					return null;
				else
					return Entity.ParentCanvas;
			}
		}


		protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
		{
			base.OnMouseDoubleClick(e);

			EditLabel();
		}


		protected TextBlock _label;
		/// <summary>
		/// The item's label.
		/// </summary>
		public string Label
		{
			get { return _label.Text; }
			set { _label.Text = value; }
		}


		protected override void ResetStyle()
		{
			base.ResetStyle();

			_label.FontSize = StyleFontSize;
		}

		/// <summary>
		/// This gets called whenever the user wants to change the label.
		/// </summary>
		public event TextChangedValidator LabelChanged;

		/// <summary>
		/// Gives the user a chance to edit the label.
		/// </summary>
		public void EditLabel()
		{
			ParentCanvas.EditText(Position, new Point(ActualWidth, (_label.Parent as FrameworkElement).ActualHeight), Label, delegate(string val)
			{
				EndEditLabel(val);
			});
		}

		/// <summary>
		/// Handles the end of an editing action of the label.
		/// </summary>
		protected virtual void EndEditLabel(string val)
		{
			bool valid = LabelChanged == null || LabelChanged(this, val);
			if (valid)
			{
				Label = val;
				var next = Entity.Children.GetNext(this);
				Entity.Children.DeselectAll();
				Entity.Children.Select(next);
				next.EditLabel();
			}
			else
				EditLabel();
		}


		#region The Entity

		private Entity _entity;
		/// <summary>
		/// The parent entity that this item belongs to.
		/// </summary>
		public virtual Entity Entity
		{
			get { return _entity; }
			set
			{
				_entity = value;
				if (value != null)
					_entity.SizeChanged += new SizeChangedEventHandler(OnEntitySizeChanged);
			}
		}

		/// <summary>
		/// Handles the entity's size changed event to adjust the width to match.
		/// </summary>
		private void OnEntitySizeChanged(object sender, SizeChangedEventArgs e)
		{
			_label.Width = Entity.Width;
		}

		#endregion


		#region Connections

		public override Point GetConnectionPoint(Point point, out Point? dir)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
